import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.Socket;

public class DownloadThread extends Thread{
    Torrent torrent;
    Socket socket;
    BufferedReader in;
    PrintWriter out;
    public void download(String torrentLink) {
        /*连接Tracker*/
        try {
            torrent = new Torrent(torrentLink);
            socket = torrent.getTrackerAddress().connectToAddress();
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
        }
        catch (Exception e) {
            System.out.println(e.toString());
            System.out.println("地址错误");
            close();
            return;
        }


    }
    public static void main(String[] args) throws IOException {
        /*1.获取.torrent文件*/
        String torrentLink = "";
        /*解析torrent文件*/
        Torrent torrent = new Torrent(torrentLink);

        torrent.setTrackerAddress(new Address("127.0.0.1", 1234));

        /*2.连接Tracker*/
        Socket socket = null;
        try {
            socket = torrent.getTrackerAddress().connectToAddress();
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            /*3.从Tracker获取下载节点地址*/

            out.println(JSONObject.toJSONString(new Message("getDownloadAddress", torrent.getIndex())));

            /*4.与资源节点建立连接*/
        }
        catch (Exception e) {
            System.out.println("下载失败");
        }
        finally {
            if (socket != null) {
                socket.close();

            }
        }


        /*5.管理资源节点*/

        /*6.和资源节点*/

    }

    public void close() {
        try {
            this.in.close();
            this.out.close();
            this.socket.close();
        }
        catch (Exception ignored){}
    }
}
